package com.technology.education.ui.student.search

import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.os.bundleOf
import com.angcyo.dsladapter.dpi
import com.angcyo.dsladapter.dslItem
import com.angcyo.dsladapter.toDslItemList
import com.google.android.flexbox.FlexboxLayout
import com.technology.education.R
import com.technology.education.base.BaseRecyclerTopBarFragment
import com.technology.education.data.model.CollectCourse
import com.technology.education.data.model.SearchModel
import com.technology.education.data.model.TeacherInfoModel
import com.technology.education.dslitem.ItemSingleText
import com.technology.education.ext.*
import com.technology.education.ui.student.course_detail.CourseDetailActivity
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.view.afterTextChange
import me.hgj.jetpackmvvm.util.startActivity
import kotlin.text.isNotEmpty

/**
 * 搜索页面
 */
class SearchFragment : BaseRecyclerTopBarFragment<SearchViewModel>() {
    override fun layoutId(): Int = R.layout.fragment_search
    override fun initViews() {
        view?.findViewById<View>(R.id.iv_back)?.setOnClickListener {
            onBack()
        }
        view?.findViewById<EditText>(R.id.et_content)?.apply {
            afterTextChange {
                mViewModel.searchKey = it
            }
            imeOptions = EditorInfo.IME_ACTION_SEARCH
            setOnEditorActionListener { _, i, _ ->
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    closeInput()
                    if (mViewModel.searchKey.isNotEmpty()) {
                        refreshData()
                    }
                }
                true
            }
            showInput(this)
        }
        initGrid(3)
        hasMore(false)
    }

    override fun lazyLoadData() {
        mViewModel.history.plus(getSearchHistory())
        setUI(null)
    }

    private fun setUI(data: SearchModel?) {
        renderAdapter {
            data?.let {
                it.courseList?.let { list ->
                    dslItem(ItemSingleText("相关课程"))
                    resetItem(list.toDslItemList(R.layout.item_course_collectioin) {
                        itemSpanCount = 1
                        itemBindOverride = { itemHolder, _, _, _ ->
                            itemData?.let { data ->
                                if (data is CollectCourse) {
                                    itemHolder.tv(R.id.tv_name)?.text = data.name
                                    itemHolder.v<ImageView>(R.id.iv_conver)?.apply {
                                        loadImage(data.url, this)
                                    }
                                    itemHolder.clickItem {
                                        startActivity(
                                            CourseDetailActivity::class,
                                            Pair("id", data.id),
                                            Pair("title", data.name),
                                            Pair("title", data.url ?: "")
                                        )
                                    }
                                }
                            }

                        }
                    })
                }

                it.teacherList?.let { list ->
                    dslItem(ItemSingleText("相关教师"))
                    appendItems(list.toDslItemList(R.layout.item_follow_teacher) {
                        itemSpanCount = -1
                        itemBindOverride = { itemHolder, _, _, _ ->
                            itemData?.let { data ->
                                if (data is TeacherInfoModel) {
                                    itemHolder.tv(R.id.tv_name)?.text = data.name
                                    itemHolder.v<ImageView>(R.id.iv_header)?.apply {
                                        header(data.avatar, this)
                                    }
                                    itemHolder.click(R.id.btn_call) { view ->
                                        navigation(
                                            view,
                                            R.id.action_searchFragment_to_publishFragment,
                                            bundleOf("id" to data.id)
                                        )
                                    }
                                }
                            }
                        }
                    })
                }
            } ?: dslItem(R.layout.item_search_history) {
                itemBindOverride = { itemHolder, _, _, _ ->
                    itemSpanCount = -1
                    itemHolder.v<FlexboxLayout>(R.id.fl_content)?.apply {
                        mViewModel.history.forEach {
                            addView(TextView(requireContext()).apply {
                                text = it
                                setTextColor(getColor(R.color.text_m))
                                textSize = 14f
                                gravity = Gravity.CENTER
                                setPadding(8 * dpi, 4 * dpi, 8 * dpi, 4 * dpi)
                                background = getResId(R.drawable.round_search_history)
                                setOnClickListener { _ ->
                                    historySearch(it)
                                }
                            })
                        }

                    }
                }
            }
        }
    }

    override fun onDestroy() {
        saveSearchHistory(mViewModel.history)
        super.onDestroy()
    }

    private fun historySearch(key: String) {
        mViewModel.searchKey = key
        view?.findViewById<EditText>(R.id.et_content)?.setText(key)
        refreshData()
    }

    override fun createObserver() {
        mViewModel.result.observe(this) {
            parseState(it, onSuccess = { data ->
                setUI(data)
            })
        }
    }
}